/**
 * Copyright ©
 * 
 * @author: zw
 * @date: 2021-11-06 
 */


import React, { FC, ReactElement, useCallback, useState, useReducer, useEffect } from 'react';
import Input from './Input'
import List from './List'
import { todoReducer } from './reducer';
import { ACTION_TYPE, IState, ITodo } from './typings';
// const initinalState: IState = {
//   todoList: []
// }

function init (initinalList: ITodo[]): IState {
  return {
    todoList: initinalList
  }
}
interface IProps {
  todoList: ITodo[],
  removeTodo: (id: number) => void,
  taggleTodo: (id: number) => void,
}
 const TodoList: FC<IProps> = (props): ReactElement => {
  // const [ todoList, setTodoList ] = useState<ITodo[]>([]);
  const [ state, dispatch ] = useReducer<ITodo[]>(todoReducer, [], init);
  useEffect(() => {
    const todoList = JSON.parse(localStorage.getItem('todoList')|| '[]');
    dispatch({
      type: ACTION_TYPE.INIT_TODOLIST,
      payload: todoList
    });
  }, [state.todoList]);

  const addTodo = useCallback((todo: ITodo) => {
      // setTodoList(todoList => [...todoList, todo]);
      dispatch({
        type: ACTION_TYPE.ADD_TODO,
        payload: todo
      });
    }, []);

    const removeTodo = useCallback((id: number):void => {
      dispatch({
        type: ACTION_TYPE.REMOVE_TODO,
        payload: id
      });
    }, []);

    const toggleTodo = useCallback((id: number):void => {
      dispatch({
        type: ACTION_TYPE.TAGGLE_TODO,
        payload: id
      });
    }, []);
  return(
    <div className="">
      <Input addTodo={ addTodo } todoList={ state.todoList }></Input>
      <List todoList={ state.todoList } removeTodo={ removeTodo } toggleTodo={ toggleTodo } ></List>
    </div>
  )
}

export default TodoList


